package com.sfx.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.sfx.domain.ResponseResult;
import com.sfx.domain.entity.LoginUser;
import com.sfx.enums.AppHttpCodeEnum;
import com.sfx.utils.JwtUtil;
import com.sfx.utils.RedisCache;
import com.sfx.utils.WebUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

import static com.sfx.constants.RedisConstants.BLOG_LOGIN_KEY;
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{

    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1.获取请求头中的token
        String token = request.getHeader("token");
        //2.判断token是否为空
        if(StrUtil.isBlank(token)) {
            //直接放行,不需要解析token.不需要验证登陆
            filterChain.doFilter(request,response);
            return;
        }
        //3.不为空,解析token
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            log.error("token超时,或者过期{}",e);
            //token超时,或者过期
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response,JSON.toJSONString(result));
            return;
        }
        //4.根据解析获取UserId
        String subject = claims.getSubject();
        long userId = Long.parseLong(subject);
        //5.根据UserId,从redis中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject(BLOG_LOGIN_KEY + userId);
        if(Objects.isNull(loginUser)) {
            log.error("token超时,或者过期,redis中不存在");
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response,JSON.toJSONString(result));
            return;
        }
        //6.保存到SecurityContextHolder中,方面后面的过滤器做验证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}